package ls

import (
	"fmt"
	"strings"

	"gitee.com/eeppee_admin/go-tuiftp/reuse"
	tea "github.com/charmbracelet/bubbletea"
)

// LsTUI 启动TUI界面浏览FTP目录
func LsTUI(path string) error {
	// 解析路径格式 [站点名称]:[远程路径]
	arr := strings.Split(path, ":")
	if len(arr) != 2 {
		return fmt.Errorf("远程路径格式错误, 正确格式: [站点名称]:[远程路径]")
	}
	siteName, remotePath := arr[0], arr[1]

	// 确保路径以/结尾
	if remotePath == "" {
		remotePath = "/"
	} else if remotePath[len(remotePath)-1] != '/' {
		remotePath += "/"
	}

	// 读取配置获取站点信息
	sysConfig := &reuse.SysConfig{}
	if err := sysConfig.Read(); err != nil {
		return fmt.Errorf("读取配置失败: %v", err)
	}

	var targetSite *reuse.SiteConfig
	for _, site := range sysConfig.Sites {
		if site.Name == siteName {
			// 复制值避免指针问题
			s := site
			targetSite = &s
			break
		}
	}

	if targetSite == nil {
		return fmt.Errorf("未找到站点: %s", siteName)
	}

	// 连接FTP服务器
	ftpClient, err := reuse.NewFtpClient(*targetSite)
	if err != nil {
		return fmt.Errorf("连接FTP失败: %v", err)
	}
	defer ftpClient.Conn.Quit()

	// 启动TUI
	m := newModel(ftpClient, targetSite, remotePath)
	p := tea.NewProgram(m, tea.WithAltScreen())
	if _, err := p.Run(); err != nil {
		return fmt.Errorf("TUI运行失败: %v", err)
	}

	return nil
}
